package com.edgclub.edg.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

import com.android.volley.VolleyError;
import com.edgclub.edg.Constant;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.FriendApi;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.param.MessageParam;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.fragment.ChatFragment;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.GroupBean;
import com.edgclub.edg.model.result.GroupListData;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.dao.DaoHelper;
import com.hyphenate.easeui.dao.GroupChatBeanDao;
import com.hyphenate.easeui.dao.UserBeanDao;
import com.hyphenate.easeui.model.ChatBean;
import com.hyphenate.easeui.model.GroupChatBean;
import com.hyphenate.easeui.model.UserBean;
import com.hyphenate.easeui.model.UserChatListData;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.util.EasyUtils;
import com.rockerhieu.emojicon.emoji.SerializeManager;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 聊天页面，需要fragment的使用{@link EaseChatFragment}
 *
 */
public class ChatActivity extends GzBaseActivity implements VolleyListener{

    public static ChatActivity activityInstance;
    private ChatFragment chatFragment;
    String toChatUsername;
    private ChatBean chatBean;
    private List<String>disturbList;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.em_activity_chat);
        activityInstance = this;
        //聊天人或群id
        disturbList= (List<String>) SerializeManager.loadFile(Constant.notDisturb+ GuZhiApplication.getInstance().getUserId()+"");
        if(null==disturbList)
            disturbList=new ArrayList<>();
        chatBean = (ChatBean) getIntent().getSerializableExtra("chatBean");
        if(chatBean.getChatType()== Constant.CHATTYPE_SINGLE){
            if(!DaoHelper.getInstance(ChatActivity.this,Constant.DB_NAME_CHAT).isHas(UserBeanDao.Properties.Imid,chatBean.getImid())){
                MessageParam messageParam = new MessageParam();
                messageParam.setUserId(GuZhiApplication.getInstance().getUserId());
                messageParam.setImids(chatBean.getImid());
                new FriendApi(this).getUserFromIm(messageParam, this);
            }else if("".equals(chatBean.getName())){
                UserBean userBean= (UserBean) DaoHelper.getInstance(this, EaseConstant.DB_NAME_CHAT).getTypeId(UserBeanDao.Properties.Imid,chatBean.getImid());
                try {
                    chatBean.setName(userBean.getNick());
                    chatBean.setGno(userBean.getGzno());
                    chatBean.setLogo(userBean.getLogo());
                    chatBean.setId(userBean.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }else if(chatBean.getChatType()== Constant.CHATTYPE_GROUP){
            if(!DaoHelper.getInstance(ChatActivity.this,Constant.DB_NAME_GROUP).isHas(GroupChatBeanDao.Properties.Ggimid,chatBean.getImid())){
                MessageParam messageParam = new MessageParam();
                messageParam.setUserId(GuZhiApplication.getInstance().getUserId());
                messageParam.setGimid(chatBean.getImid());
                new FriendApi(this).getGroupFromIm(messageParam, this);
            }else if("".equals(chatBean.getName())){
                GroupChatBean userBean= (GroupChatBean) DaoHelper.getInstance(this, EaseConstant.DB_NAME_GROUP).getTypeId(GroupChatBeanDao.Properties.Ggimid,chatBean.getImid());
                chatBean.setName(userBean.getGname());
                chatBean.setGroupid(userBean.getGroupid());
                chatBean.setLogo(userBean.getLogo());
                chatBean.setGno(userBean.getGno());
            }
        }
        toChatUsername=chatBean.getImid();
//        toChatUsername = getIntent().getExtras().getString("userId");
        //可以直接new EaseChatFratFragment使用
        chatFragment = new ChatFragment();
        //传入参数
        chatFragment.setArguments(getIntent().getExtras());
        chatFragment.setDisturbList(disturbList);
        getSupportFragmentManager().beginTransaction().add(R.id.container, chatFragment).commit();
        
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        // 点击notification bar进入聊天页面，保证只有一个聊天页面
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }

    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (null!=chatFragment) {
            chatFragment.onKeyDown(keyCode, event);
        }
        return false;
    }
    @Override
    public void onBackPressed() {
        chatFragment.onBackPressed();
        try {
            EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                    ThreadEnforcer.MAIN).unregister(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (EasyUtils.isSingleActivity(this)) {
            Intent intent = new Intent(this, GzMainActivity.class);
            startActivity(intent);
        }
    }
    
    public String getToChatUsername(){
        return toChatUsername;
    }

    @Override
    public void onStart(String tag) {

    }

    @Override
    public void onSuccess(String response, String tag) {
        if (JSONHelper.isSuccess(response)) {
            if (tag.equals(ApiConfig.APIURL.URL_From_USER)) {
                UserChatListData data = JsonUtil.getMode(response,
                        UserChatListData.class);
                if(null!=data&&null!=data.getData()) {
                    for (UserBean user : data.getData()) {
                        DaoHelper.getInstance(ChatActivity.this,Constant.DB_NAME_CHAT).insert(user);
                    }

                }
            }else if(tag.equals(ApiConfig.APIURL.URL_From_GROUP)){
                GroupListData data = JsonUtil.getMode(response,
                        GroupListData.class);
                if(null!=data&&null!=data.getData()) {
                    for (GroupBean groupBean : data.getData()) {
                        if(!DaoHelper.getInstance(ChatActivity.this,Constant.DB_NAME_GROUP).isHas(GroupChatBeanDao.Properties.Ggimid,groupBean.getGimid()))
                            DaoHelper.getInstance(ChatActivity.this,Constant.DB_NAME_GROUP).insert(groupBean);
                        else
                            DaoHelper.getInstance(ChatActivity.this,Constant.DB_NAME_GROUP).update(groupBean);
                    }
                }
            }

            HashMap<String, Object> hashMap = new HashMap<String, Object>();
            hashMap.put("event", BroadCastEvent.CHATLIST_REFRESH);
            EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                    ThreadEnforcer.MAIN).post(hashMap);
        }
    }

    @Override
    public void onFaile(VolleyError volleyError, String tag) {
        ResultCode.toastVolleyError(this, volleyError);
    }

    @Subscribe
    public void quitGroup(HashMap<String, Object> map){
        String event = (String) map.get("event");
        boolean isQuit = (boolean) map.get("obj");
        if (null!=event&&BroadCastEvent.BB_GROUP_REFUL.equals(event) && isQuit) {
            finish();
        }
    }


}
